//
//  FirstWidget.swift
//  FirstWidget
//
//  Created by alanzhangg on 2023/6/18.
//

import WidgetKit
import SwiftUI

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date())
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), text: "two")
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []

        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        let entryDate = Calendar.current.date(byAdding: .minute, value: 2, to: currentDate)!
        let entry = SimpleEntry(date: currentDate, text: "hourOffset")
        entries.append(entry)

        let timeline = Timeline(entries: entries, policy: .after(entryDate))
        completion(timeline)
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    var text: String = "one"
}

struct FirstWidgetEntryView : View {
    
    @Environment(\.widgetFamily) var family: WidgetFamily
    var entry: Provider.Entry
    

    var body: some View {
        VStack{
            Text(entry.date, style: .time)
                .padding(.top, 10)
            Text(entry.text)
        }
        .containerBackground(for: .widget) {
            Rectangle()
                .fill(Color.blue)
        }
        .widgetURL(URL.init(string: "com.sss"))
        
    }
}

struct FirstWidget: Widget {
    let kind: String = "FirstWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            FirstWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge, .systemExtraLarge])
    }
}

struct FirstWidget_Previews: PreviewProvider {
    static var previews: some View {
        FirstWidgetEntryView(entry: SimpleEntry(date: Date()))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}
